﻿var fn = {
    //使用$.request替换该方法
    queryStr: function (name) {
        return $.request(name);
    },
    setQueryStr: function (url, name, qstr) {
        if (qstr) {
            var qv = $.request(name, url);
            var qparam = name + "=" + qstr;
            if (qv) {
                return url.replace(name + "=" + qv, qparam);
            } else {
                return url + (url.indexOf("?") == -1 ? "?" : "&") + qparam;
            }
        }
        return url;
    },
    hide: function (o) {
        if (typeof o != "object")
            o = document.getElementById(o);
        if (o) {
            o.style.display = "none";
        }
    },
    tipDialog: function (option) {
        var head = option.head || "提示";
        var content = option.content || "";
        var width = option.width || 200;
        var $overlay = $("<div class='tipDialog-overlay'></div>");
        var $tipDialog = $("<div id='tipDialog'><div class='head'>" + head + "<span class='close-btn'>×</span></div><div class='content'>" + content + "</div></div>");
        $tipDialog.css({
            "width": width + "px",
            "margin": "-100px 0 0 " + (-width / 2) + "px"
        })
        $overlay.appendTo("body");
        $tipDialog.appendTo("body");
        var $clostBtn = $tipDialog.find(".close-btn");
        $clostBtn.click(function () {
            $tipDialog.remove();
            $overlay.remove();
        })
    }
}

$.extend({
    //获取url中的参数
    request: function (name, url) {
        var vars = [], hash;
        var url = url || window.location.href;
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = decodeURIComponent(hash[1]);
        }
        if (name && name != "") {
            return vars[name];
        } else {
            return vars;
        }
    }
});
/*
异步完成后执行的事件
*/
var AjaxBegin = function (r, a) {
    $("#pagelistId").fadeOut(200, function () {
        var o = $("#pageloading");
        if (o == null || o.length == 0) {
            $("#pagelistId").before('<div id="pageloading" class="pageloading"> <img src="/Resources/img/loading.gif" /> 数据加载....</div>');
        } else {
            $("#pageloading").show();
        }
    });
}

var AjaxSuccess = function (r, a, b, c) {
    gridviewInit();
    $("#pageloading").hide();
}

var AjaxFailure = function (r, a, b, c) {
    $("#pageloading").hide();
}

var AjaxComplete = function (r, a, b, c, d) {
    var fun = function () {
        $('#pagelistId').fadeIn(300);
        $("#pageloading").hide();
    }
    setTimeout(fun, 200);

    var initselect = $("#btn_at_selectAll");
    if (initselect != null && initselect != undefined) {
        $("#btn_at_selectAll").click(function () {
            var chek = $(this).is(":checked");
            var item = $("#pagelistId table tr td input[type='checkbox']");
            var ids = "";
            for (var i = 0; i < item.length; i++) {
                item[i].checked = $(this).is(":checked");
                if (item[i].checked) {
                    ids += item[i].name + ",";
                }
            }
            $("#selectids").val(ids);
        });
        $("#pagelistId table tr td input[type='checkbox']").click(function () {
            var item = $("#pagelistId table tr td input[type='checkbox']");
            var ids = "";
            for (var i = 0; i < item.length; i++) {
                if (item[i].checked) {
                    ids += item[i].name + ",";
                }
            }
            $("#selectids").val(ids);
        });
    }
}
/*
异步开始执行的事件
*/
var OnSubmitBegin = function () {
    var btn = $("#btnPay");
    if (btn != undefined && btn != null) {
        btn.val("正在处理中...");
        btn.attr("disabled", true);
    }
}

var OnSubmitSuccess = function (o)
{
    var btn = $("#btnPay");
    if (btn != undefined && btn != null) {
        btn.val("保存");
        btn.attr("disabled", false);
    }

    if(o != null)
    {
        if (o.success) {
            swal({
                title: "操作提示",
                text: o.msg,
                type: "success",
                closeOnConfirm: true,
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            }, function () {
                if (o.url != null && o.url != undefined) {
                    window.location.href = o.url;
                }
        });
        }
        else {
            swal({
                title: "操作提示",
                text: o.msg,
                type: "warning",
                closeOnConfirm: false,
                confirmButtonText: "确定",
                cancelButtonText: "取消"
            });
        }
    }
}

$(function () {
    $("#btn_at_selectAll").click(function () {
        var chek = $(this).is(":checked");
        var item = $("#pagelistId table tr td input[type='checkbox']");
        var ids = "";
        for (var i = 0; i < item.length; i++) {
            item[i].checked = $(this).is(":checked");
            if (item[i].checked) {
                ids += item[i].name + ",";
            }
        }
        $("#selectids").val(ids);
    });
    $("#pagelistId table tr td input[type='checkbox']").click(function () {
        var item = $("#pagelistId table tr td input[type='checkbox']");
        var ids = "";
        for (var i = 0; i < item.length; i++) {
            if (item[i].checked) {
                ids += item[i].name + ",";
            }
        }
        $("#selectids").val(ids);
    });
    //退出系统
    $("ul>li>.loginout-sys").click(function () {
        swal({
            title: "操作提示",
            text: "你确定要退出系统吗？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            closeOnConfirm: false
        }, function () {
            window.location.href = '/Admin/Index/LoginOut';
        });
    });
    //初始化表格
    gridviewInit(true);
});

$.prototype.live = function (types, data, fn) {
    jQuery(this.context).on(types, this.selector, data, fn);
    return this;
}

//公共的脚本方法集
var ml = {
    options: {
        //弹框对象
        mlmsg: function (o) {
            var o = o || "dialog";
            return typeof o == "object" ? o : $("#" + o);
        },
        //弹框默认属性
        DdialogOpt: { width: 300, height: 200 }
    },
    fn: {
        //使用$.request替换该方法
        queryStr: function (name) {
            return $.request(name);
        },
        setQueryStr: function (url, name, qstr) {
            if (qstr) {
                var qv = $.request(name, url);
                var qparam = name + "=" + qstr;
                if (qv) {
                    return url.replace(name + "=" + qv, qparam);
                } else {
                    return url + (url.indexOf("?") == -1 ? "?" : "&") + qparam;
                }
            }
            return url;
        },
        hide: function (o) {
            if (typeof o != "object")
                o = document.getElementById(o);
            if (o) {
                o.style.display = "none";
            }
        },
        centerTips: function (o, msg, options) {
            var options = options || {};
            $(o).html(msg).show("slide", options, 500, function () {
                setTimeout(function () { $(o).hide(); }, 2000);
            });
        },
        enterToClick: function (tobj, btn) {
            $(tobj).keydown(function (evt) {
                var event = (evt) ? evt : ((window.event) ? window.event : "");
                if (event.keyCode == 13) {
                    $(btn).click();
                }
            });
        },
        treeRecurrent: function (top, flag) {
            if (top && top.childList) {
                for (var i = 0; i < top.childList.length; i++) {
                    top.childList[i].select(flag);
                }
            }
        }
    },
    el: {
        tabs: function (o, s, _fun) {
            if (!o) return;
            var s = s || "ul li";
            var getEid = function (at) {
                return at.href.substr(at.href.indexOf("#"));
            }

            var lis = new Array();
            var alis = new Array();
            if ($(o).attr("class") && $(o).attr("class") != "" && $(o).attr("class").indexOf("el_tabs") == -1) {
                $(o).attr("class", "el_tabs " + $(o).attr("class"));
            }
            $(o).find(s + " a").each(function (i) {
                alis.push(this);
                var od = getEid(this);
                $(od).attr("class", ($(od).attr("class") || "") + " element");
                $(od).hide();
                lis.push(od);
                $(this).click(function () {
                    $(alis).each(function () {
                        var css = $(this).parent().attr("class");
                        $(this).parent().attr("class", css ? css.replace("hover", "") : "");
                    });
                    $(this).parent().attr("class", ($(this).parent().attr("class") || "") + " hover");
                    var id = getEid(this);
                    $(lis).each(function (i) {
                        if (lis[i] == id) {
                            $(lis[i]).show();
                            if (_fun) {
                                _fun();
                            }
                        } else {
                            $(lis[i]).hide();
                        }
                    });
                    return false;
                });
            });

            $(alis[0]).click();
        }
    },
    /*
    判断是否登录超时并处理
    r:返回的json数据
    */
    checkSign: function (r) {
        if (r) {
            if (r.url && r.success === false) {
                if (r.url.toLowerCase().indexOf("/index/login") > -1) {
                    alert(r.msg);
                    top.location.href = r.url;
                    return true;
                }
            }
        }
        return false;
    },
    /*
    setting 操作方法
    */
    setaction: function (mlmsg, _ptreeId, _posturl, _data, _url, _title, toptions, doption) {
        var mlmsg = ml.options.mlmsg(mlmsg);
        var isPostAction = (_posturl && _posturl != "") ? false : _data;
        var treeId = "tree_" + _ptreeId + "_" + _data;
        if (isPostAction) {
            _data = $("#" + isPostAction).attr("value");
        }
        var tree = document.getElementById(treeId);
        var opt = $.extend({
            title: _title,
            modal: true,
            buttons: {
                "全选/取消[提示：可双击进行快速选择]": function () {
                    ml.setaction.param_all = ml.setaction.param_all || "true";
                    $("#" + treeId).dynatree("getRoot").visit(function (node) {
                        if (!node.data.hideCheckbox) {
                            node.select(ml.setaction.param_all == "true");
                        }
                        //node.toggleSelect();
                    });
                    ml.setaction.param_all = ml.setaction.param_all == "true" ? "false" : "true";
                },
                "确定": function (evt) {
                    var btn = evt.currentTarget;
                    var btnText = btn.firstChild;
                    btnText.innerHTML = "正在处理…";
                    btn.disabled = true;
                    var stopOnParents = doption && doption.stopOnParents;
                    var trees = $("#" + treeId).dynatree("getTree");
                    var ids = "", names = "";
                    $(trees.serializeArray(stopOnParents)).each(function (i) {
                        var o_t = trees.getNodeByKey(this.value)
                        ids += this.value + ",";
                        names += o_t.data.title + ",";
                    });
                    //当提交地址为空的时候判断为在当前页面进行赋值操作
                    if (!isPostAction) {
                        $.post(_posturl, { data: ids, oid: _data }, function (r) {
                            btn.disabled = false;
                            btnText.innerHTML = "确定";
                            $(mlmsg).dialog("close");
                            mlmsg.html(r.msg).dialog({
                                title: "提示",
                                modal: true,
                                buttons: {
                                    "确定": function () {
                                        $(this).dialog("close");
                                        location.href = location.href;
                                    }
                                }
                            });
                        });
                    } else {
                        $("#" + isPostAction).attr("value", ids);
                        $("#" + _ptreeId).html(names == "" ? "请选择" : "已选择：" + names);
                        var clearId = $("#" + _ptreeId).attr("clearid");
                        var oClear = document.getElementById(clearId);
                        if (oClear) {
                            names == "" ? $(oClear).hide() : $(oClear).show();
                        }
                        btn.disabled = false;
                        $(this).dialog("close");
                    }
                }
                , "取消": function () {
                    $(this).dialog("close");
                }
            }
        }, ml.options.DdialogOpt);
        opt = $.extend(opt, doption);
        mlmsg.html('<div id="' + treeId + '"></div>')
        $.post(_url, { data: _data }, function (r) {
            r = eval(r);
            if (ml.checkSign(r)) return;
            toptions = $.extend({
                autoFocus: false,
                checkbox: true,
                selectMode: 3,
                children: r,
                fx: { height: "toggle", duration: 200 },
                autoCollapse: true,
                onLazyRead: function (node) {
                    node.appendAjax({ url: _url, data: { data: _data, pid: node.data.key }, success: function () { } });
                },
                onSelect: function (isSelected, o) {
                    //自定义选择方式
                    switch (this.options.selectMode) {
                        case 10: //选中父级时自动选中所有子级，反则取消所有子级；取消单个子级时父级不变化；                            
                            ml.fn.treeRecurrent(o, isSelected)
                            break;
                    }
                }
            }, toptions);
            $("#" + treeId).dynatree(toptions);
            mlmsg.dialog(opt);
        });
    },
    /*
    角色设置
    */
    roleSetting: function (o, isClear, cid) {
        var o = typeof o == "object" ? o : document.getElementById(o);
        var vid = $(o).attr("vid");
        var clearid = $(o).attr("clearid");
        if (!isClear) {
            var u = '/action/GetRolesTree?usercode=' + cid;
            var p = $(o).attr("param");
            if (p) {
                u += "&" + p;
            }
            ml.setaction(null, o.id, '', vid, u, '所属角色', { selectMode: 10 }, { width: 400, height: 300 });
        } else {
            o.innerHTML = "请选择";
            $("#" + vid).attr("value", "");
            $("#" + clearid).hide();
        }
    },
    right_actions: function (o, at, data) {
        if (o) {
            var at = o.actiontype || at || $(o).attr("actiontype");
            if (!at || at == "") {
                //从id值中获取actiontype
                if (!o.id || o.id.indexOf("btn_at_") == -1) return;
                at = o.id.substr(7);
                if (at == "") return;
            }
            at = at.toLowerCase();
            var mlmsg = $("#dialog");
            var url = o.curl || $(o).attr("curl");
            if (!url || url.length == 0) {
                url = o.url || $(o).attr("url");
            }
            switch (at) {
                case "add": //进行页面跳转操作
                case "view":
                    if (!url) return;
                    location.href = url;
                    break;
                case "edit":
                    if (!url) return;
                    if (url.indexOf("?") > -1 && url.indexOf("id=") > -1) {
                        location.href = url;
                    } else {
                        var data = data || right_actions(o, "selectAll");
                        data = data.split(',')[0];
                        location.href = (url.indexOf("?") > -1) ? url + "&id=" + data : url + "?id=" + data;
                    }
                    break;
                case "back":  //返回
                    var burl = url || $(o).attr("burl");
                    if (burl) {
                        location.href = burl;
                    } else {
                        var bu = document.referrer;
                        if (bu) {
                            //后台页面跳转所传递翻页参数固定为page与ppage，且返回列表页的翻页参数固定为page；如有变动则需要对应修改
                            var q = $.request("page");
                            bu = ml.fn.setQueryStr(bu, q ? "page" : "ppage", q || $.request("ppage"));
                            location.href = bu;
                        } else {
                            history.go(-1);
                        }
                    }
                    break;
                case "selectall": //全选
                    if (true) {
                        var chek = o && o.id && o.id == "btn_at_selectAll";
                        var pid = data || "pagelistId";
                        var item = $("#" + pid + " :checkbox");
                        var ids = "";
                        for (var i = 0; i < item.length; i++) {
                            if (chek) {
                                item[i].checked = o.checked;
                            }
                            if (item[i].checked) {
                                ids += item[i].name + ",";
                            }
                        }
                        return ids;
                    }
                    break;
                case "setting":  //权限树
                    if (true) {
                        var purl = url.toLowerCase().substr(0, url.indexOf("?"));
                        var title = $(o).text();
                        switch (purl) {
                            case "rolerightssetting":
                                if (true) {
                                    ml.setaction(mlmsg, purl, url, data, "/Action/GetRoleRightsTree", title || "角色权限设置", { selectMode: 10 }, { width: 450, height: 400 });
                                }
                                break;
                        }
                    }
                    break;
                case "delete":
                case "recover":
                case "publish":
                case "insert":
                case "unpublish":
                case "top":
                case "untop":
                case "closed":
                    if (true) {
                        var smsg = o.value || o.innerHTML;
                        var msgs = {
                            "delete": smsg,
                            "recover": smsg,
                            "publish": smsg,
                            "unpublish": smsg,
                            "insert": smsg,
                            "closed": smsg,
                            "recommend": smsg,
                            "unrecommend": smsg,
                            "top": smsg,
                            "untop": smsg,
                            "quote": smsg
                        }

                        var isNoTipSelectAll = $.request("_ulp_right_action_notip_selectall", url) === "1";
                        var msgs = ["请选择需要" + msgs[at] + "的选项.", "是否确定 " + msgs[at] + " ?"];
                        var data = data || right_actions(o, "selectAll");
                        if (!isNoTipSelectAll && (!data || data == "")) {
                            mlmsg.html(msgs[0]).dialog({
                                title: "提示",
                                width: 308,
                                height: 150,
                                modal: true,
                                buttons: {
                                    "确定": function () {
                                        $(this).dialog("close");
                                    }
                                }
                            });
                            return;
                        }

                        var action_ok = function () {
                            ml.ajaxWaitDialog(false, null, { autoClose: 15000 });

                            url += (url.indexOf("?") > -1 ? "&" : "?") + Math.random() + "&" + new Date().toTimeString();
                            //获取当前页为操作动作后跳转回当前页
                            var page = $("#___hide_currentpageindex").val();
                            if (page && page > 0) {
                                url = ml.fn.setQueryStr(url, "page", page);
                            }
                            $.post(url, { data: data }, function (r) {
                                try {
                                    ml.ajaxWaitDialog(true);
                                    if (r && r.msg) {
                                        var s = function () {
                                            if (r.jsfun) {
                                                try {
                                                    var fun = eval('(' + r.jsfun + ')');
                                                } catch (e) {
                                                    alert(e.message);
                                                }
                                            } else {
                                                if (r.url) {
                                                    location.href = r.url;
                                                }
                                            }
                                        }
                                        if (!ml.ajaxWaitDialog(false, r.msg, { callback: s, autoClose: 2000 })) {
                                            alert(r.msg);
                                            s();
                                        }

                                    } else {
                                        var s = function () {
                                            var update = document.getElementById("pagelistId");
                                            if (update) {
                                                update.outerHTML = r;
                                            }
                                            AjaxSuccess();
                                        }
                                        if (!ml.ajaxWaitDialog(false, "操作完成", { callback: s, autoClose: 2000 })) {
                                            s();
                                            ml.fn.centerTips(".head .headtips", "操作完成");
                                        }
                                    }
                                } catch (e) {
                                    alert(e.Message);
                                }

                            });
                            $(this).dialog("close");
                        };

                        var isNoTip = $.request("_ulp_right_action_notip", url) === "1";
                        if (isNoTip) {
                            action_ok();
                        } else {
                            mlmsg.html(msgs[1]).dialog({
                                title: "提示",
                                width: 308,
                                height: 150,
                                modal: true,
                                buttons: {
                                    "确定": action_ok
                                    , "取消": function () {
                                        $(this).dialog("close");
                                    }
                                }
                            });
                        }
                    }
                    break;

                case "ajaxsubmitbegin":
                    if (true) {
                        ml.ajaxWaitDialog(false);
                    }
                    break;

            }
        }
    },
    /*
    操作进行时等候提示信息栏
    */
    ajaxWaitDialog: function (isclose, msg, opt) {
        if (window.easyDialog) {
            var wait = 200000;
            var msg = msg || "<img alt='loading' src='/Resources/easydialog/loading.gif' /> 处理中...";

            var options = $.extend({
                container: {
                    header: '提示',
                    content: msg,
                    style: { width: "auto", minWidth: "180px", maxWidth: "360px", textAlign: "center", height: "100%" }
                },
                autoClose: wait,
                drag: false
            }, opt);

            if (isclose) {
                window.easyDialog.close();
            } else {
                window.easyDialog.open(options);
            }
            return true;
        }
        return false;
    }
};

var gridviewInit = function (isinit) {
    /*
    初始化按钮操作 id值存在 btn_at_ 的事件
    */
    if (isinit) {
        $(":input").each(function (i) {
            var o = this;
            if (this.id.indexOf("btn_at_") == 0) {
                //$(this).attr("onclick", "right_actions(this)");
                $(this).click(function () {
                    right_actions(this);
                });
            } else if (this.id.indexOf("uploadify") == 0) {
                ml.setUploadify(this);
            }
        });
    } else {
        $("#pagelistId input").each(function (i) {
            var o = this;
            if (this.id.indexOf("btn_at_") == 0) {
                $(this).attr("onclick", "right_actions(this)");
            } else if (this.id.indexOf("uploadify") == 0) {
                ml.setUploadify(this);
            }
        });
    }
}
//页面调用right_actions(para);
var right_actions = ml.right_actions;


